package com.regis.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.regis.entity.db.*;
import com.regis.entity.dto.DishDto;
import com.regis.entity.vo.ResultVo;
import com.regis.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 计算机系 ITAEM 纱雾休比我老婆
 * @Description 菜品界面接口
 * @date 2022/7/29 19:17
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CacheManager cacheManager;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @CacheEvict(value = "dish",allEntries = true)
    @PostMapping()
    public ResultVo<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return ResultVo.success("新增菜品成功");
    }

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Cacheable(value = "dish",key = "#page + '_' + #pageSize",condition = "#name == null ",unless = "#result.data == null")
    @GetMapping("/page")
    public ResultVo<Page<DishDto>> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoInfo = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoInfo, "records");

        List<Dish> dishes = pageInfo.getRecords();

        HashSet<Long> longs = new HashSet<>();
        ArrayList<Long> ids = new ArrayList<>();
        for (Dish d : dishes) {
            if (longs.add(d.getCategoryId())) {
                ids.add(d.getCategoryId());
            }
        }
        List<Category> categories = categoryService.listByIds(ids);
        HashMap<Long, String> map = new HashMap<>();
        for (Category c : categories) {
            map.put(c.getId(), c.getName());
        }

        List<DishDto> dishDtos = dishes.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            dishDto.setCategoryName(map.get(categoryId));

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoInfo.setRecords(dishDtos);

        return ResultVo.success(dishDtoInfo);
    }

    /**
     * 根据id查询菜品信息和口味信息
     *
     * @param id
     * @return
     */
    @Cacheable(value = "dish",key = "#id",unless = "#result.data == null")
    @GetMapping("/{id}")
    public ResultVo<DishDto> get(@PathVariable Long id) {
        return ResultVo.success(dishService.getByIdWithFlavor(id));
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @CacheEvict(value = "dish",allEntries = true)
    @PutMapping
    public ResultVo<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return ResultVo.success("修改成功");
    }

    /**
     * 根据id删除菜品
     *
     * @return
     */
    @CacheEvict(value = "dish",allEntries = true)
    @DeleteMapping
    public ResultVo<String> delete(Long... ids) {
        dishService.deleteWithFlavor(ids);
        return ResultVo.success("删除成功");
    }

    /**
     * 根据id修改菜品售卖状态
     *
     * @param type
     * @param ids
     * @return
     */
    @CacheEvict(value = {"dish","setMeal"},allEntries = true)
    @PostMapping("/status/{type}")
    @Transactional
    public ResultVo<String> status(@PathVariable int type, Long... ids) {
        ArrayList<Dish> dishes = new ArrayList<>();

        //判断菜品与套餐是否有关联
        List<SetmealDish> setmealDishes =
                setmealDishService.list(new LambdaQueryWrapper<SetmealDish>().in(SetmealDish::getDishId,
                        Arrays.asList(ids)));
        //若有关联，则将对应的套餐停售
        if (setmealDishes.size() > 0 && type == 0) {
            HashSet<Long> setmealIds = new HashSet<>();
            ArrayList<Setmeal> setmeals = new ArrayList<>();
            for (SetmealDish s : setmealDishes) {
                if (setmealIds.add(s.getSetmealId())) {
                    Setmeal setmeal = new Setmeal();
                    setmeal.setStatus(0);
                    setmeal.setId(s.getSetmealId());
                    setmeals.add(setmeal);
                }
            }
            setmealService.updateBatchById(setmeals);
        }

        for (Long l : ids) {
            Dish dish = new Dish();
            dish.setStatus(type);
            dish.setId(l);
            dishes.add(dish);
        }

        dishService.updateBatchById(dishes);

        return ResultVo.success("修改状态成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    @Cacheable(value = "dish",key = "#dish.categoryId",unless = "#result.data == null")
    @GetMapping("/list")
    public ResultVo<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //查询状态是1（起售）
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(queryWrapper);
        ArrayList<Long> dishIds = new ArrayList<>();
        dishList.forEach(d -> {
            dishIds.add(d.getId());
        });
        List<DishFlavor> dishFlavors = dishFlavorService.list(
                new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId,dishIds));

        HashMap<Long, ArrayList<DishFlavor>> map = new HashMap<>();
        dishFlavors.forEach(dishFlavor -> {
            if (map.get(dishFlavor.getDishId())==null){
                map.put(dishFlavor.getDishId(),new ArrayList<>());
                map.get(dishFlavor.getDishId()).add(dishFlavor);
            } else {
                map.get(dishFlavor.getDishId()).add(dishFlavor);
            }
        });

        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            dishDto.setFlavors(map.get(dishDto.getId()));
            return dishDto;
        }).collect(Collectors.toList());

        return ResultVo.success(dishDtoList);
    }
}
